<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Exception;
use think\Db;
use app\common\library\ParkService;
use app\admin\model\park\ParkingPlace;
use app\admin\model\park\Order;

class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function index()
    {
        $id = $this->request->get('id');
        if(!$id) {
            $this->error('未指定id');
        }
        $type = $this->request->param('type');
        $model = ParkingPlace::where('id', $id)->find();
        
        
        if($this->request->isPost()){
            try {
                if($type == 'pay') {
                    $order = ParkService::PreLeave($id);
                    // 测试，不支付直接放行
                    ParkService::Leave($order->id);
                    $model = ParkingPlace::where('id', $id)->find();
                } else {
                    $order = ParkService::CreateOrder($id, 0);
                    $model->status = 'charging';
                    $this->view->assign('fee', ['amount' => 0, 'mins' => 0]);
                    $this->view->assign('order', $order);
                }
              
            } catch (\Throwable $th) {
                $this->error($th->getMessage());
            }

        } else {
           
            if($model['status'] == 'charging') {
                $order = Order::where('parking_place_id', $id)
                    ->where('pay_status', 'pendding')
                    ->order('id', 'desc')
                    ->find();
                $fee = ParkService::CalcFee($id);
                $this->view->assign('fee', $fee);
                $this->view->assign('order', $order);
            }
        }
        $this->view->assign('model', $model);
        return $this->view->fetch();
    }

}
